﻿using System;
using System.Collections.Generic;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using System.Linq;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Controls.Primitives;

namespace OpenRPOSMetro
{
    public sealed partial class CloseOrder : Page
    {
        public event EventHandler CloseRequested;
        public int iCurrentSeat = 0;
        decimal decCurrentTotal = 0;
        public int iSplitCount = 0;
        public int iOrderNO = -1;
        public int iTableNO = -1;
        private ListView lvMenuItems = null;  // 

        private int orderDiscount = -1;  // Set DiscountID For Whole Order
        bool IsDiscount = false;  //  Discount is Applied or not  
        public int iOrderDiscount
        {
            get
            {
                return orderDiscount;
            }
            set
            {
                orderDiscount = value;
                if (IsDiscount == false && orderDiscount > 0) IsDiscount = true;
            }
        }
        
        public CloseOrder()
        {
            this.InitializeComponent();
        }

        public void addChecks(int CheckCount)
        {
            decCurrentTotal = 0;
            int tmpCount = 0;
            while (tmpCount < CheckCount)
            {
                addCheck(tmpCount); // dynamically create new container for number of split checks
                tmpCount++;
            }
        }
    
        public void addOrderDetailItem(ItemCollection itemCollection)
        {
            // Add passed item to the list
            lvMenuItems = new ListView();   // main list view container by whick we can move item to other check 

            foreach (OrderData od in itemCollection)
            {
                if (od.Discount) //  check if it is discount item
                {
                    if (IsDiscount == false && od.DiscountID != 0) IsDiscount = true; // set  discount  if it is item wise 
                    continue;
                }

                lvMenuItems.Items.Add(od);
                lvMenuItems.ScrollIntoView(od);
                decCurrentTotal += od.Price;
            }
        }

        private void addCheck(int CheckCount)
        {
            addCheck(CheckCount, false);
        }

        private async void addCheck(int CheckCount, bool IsNewCheck)
        {
            try
            {
                Canvas tmpCanvas = new Canvas();
                tmpCanvas.Margin = new Thickness(((300 * CheckCount)), 0, 0, 0);

                Border tmpBorder = new Border();
                tmpBorder.BorderThickness = new Thickness(2);
                tmpBorder.BorderBrush = new SolidColorBrush(Colors.Black);
                tmpBorder.Background = new SolidColorBrush(Colors.LightGray);
                tmpBorder.HorizontalAlignment = HorizontalAlignment.Left;
                tmpBorder.VerticalAlignment = VerticalAlignment.Top;
                tmpBorder.Width = 300;
                tmpBorder.Height = 590;

                Grid GridSplitCheck = new Grid();
                GridSplitCheck.Margin = new Thickness(2);
                RowDefinition gridRow1 = new RowDefinition();
                gridRow1.Height = new GridLength(40);
                RowDefinition gridRow2 = new RowDefinition();
                gridRow2.Height = new GridLength(40);
                RowDefinition gridRow3 = new RowDefinition();
                gridRow3.Height = new GridLength(145);
                RowDefinition gridRow4 = new RowDefinition();
                gridRow4.Height = new GridLength(40);

                RowDefinition gridRow5 = new RowDefinition();
                gridRow5.Height = new GridLength(230);

                RowDefinition gridRow6 = new RowDefinition();
                gridRow6.Height = new GridLength(90);

                GridSplitCheck.RowDefinitions.Add(gridRow1);
                GridSplitCheck.RowDefinitions.Add(gridRow2);
                GridSplitCheck.RowDefinitions.Add(gridRow3);
                GridSplitCheck.RowDefinitions.Add(gridRow4);
                GridSplitCheck.RowDefinitions.Add(gridRow5);
                GridSplitCheck.RowDefinitions.Add(gridRow6);

                #region create header strip row
                /*create header strip row*/
                Grid GridSplitCheckHeaderstrip = new Grid();
                GridSplitCheckHeaderstrip.Background = new SolidColorBrush(Colors.LightGray);
                ColumnDefinition gridColstrip1 = new ColumnDefinition();

                GridSplitCheckHeaderstrip.ColumnDefinitions.Add(gridColstrip1);
                ColumnDefinition gridColstrip2 = new ColumnDefinition();
                gridColstrip2.Width = new GridLength(40);
                GridSplitCheckHeaderstrip.ColumnDefinitions.Add(gridColstrip2);
                TextBlock lblHeaderstrip = new TextBlock();
                lblHeaderstrip.Text = "Check # " + (CheckCount + 1);
                lblHeaderstrip.FontSize = 20;
                lblHeaderstrip.Margin = new Thickness(5, 4, 0, 0);
                Grid.SetColumn(lblHeaderstrip, 0);
                GridSplitCheckHeaderstrip.Children.Add(lblHeaderstrip);

                Border tmpBorderstrip = new Border();
                tmpBorderstrip.BorderThickness = new Thickness(2);
                tmpBorderstrip.BorderBrush = new SolidColorBrush(Colors.Black);

                tmpBorderstrip.Child = GridSplitCheckHeaderstrip;
                Grid.SetRow(tmpBorderstrip, 0);
                GridSplitCheck.Children.Add(tmpBorderstrip);
                #endregion

                #region create header row

                /*create header row*/
                Grid GridSplitCheckHeader = new Grid();
                GridSplitCheckHeader.Background = new SolidColorBrush(Colors.LightGray);
                ColumnDefinition gridCol1 = new ColumnDefinition();
                ColumnDefinition gridCol2 = new ColumnDefinition();

                GridSplitCheckHeader.ColumnDefinitions.Add(gridCol1);
                GridSplitCheckHeader.ColumnDefinitions.Add(gridCol2);

                TextBlock lblHeader1 = new TextBlock();
                lblHeader1.Text = "Item";
                lblHeader1.FontSize = 20;
                lblHeader1.Margin = new Thickness(5, 4, 0, 0);
                Grid.SetColumn(lblHeader1, 0);

                TextBlock lblHeader2 = new TextBlock();
                lblHeader2.Text = "Price";
                lblHeader2.FontSize = 20;
                lblHeader2.HorizontalAlignment = HorizontalAlignment.Right;
                lblHeader2.Margin = new Thickness(0, 4, 15, 0);
                Grid.SetColumn(lblHeader2, 1);

                GridSplitCheckHeader.Children.Add(lblHeader1);
                GridSplitCheckHeader.Children.Add(lblHeader2);

                Grid.SetRow(GridSplitCheckHeader, 1);
                GridSplitCheck.Children.Add(GridSplitCheckHeader);
                #endregion

                #region create item list row


                /*create item list row*/
                ListView lstMenuItems = new ListView();
                lstMenuItems.HorizontalAlignment = HorizontalAlignment.Center;
                lstMenuItems.Height = 145;
                lstMenuItems.Margin = new Thickness(0);
                lstMenuItems.BorderThickness = new Thickness(0);
                lstMenuItems.Background = new SolidColorBrush(Colors.White);
                lstMenuItems.VerticalAlignment = VerticalAlignment.Top;
                lstMenuItems.Width = 296;
                lstMenuItems.ItemContainerStyle = this.Resources["ListViewItemStyleOpenRPOS"] as Style;
                lstMenuItems.IsSwipeEnabled = false;
                lstMenuItems.SelectionMode = ListViewSelectionMode.Multiple;
                lstMenuItems.Tag = CheckCount;
                lstMenuItems.ItemTemplate = MenuItems.ItemTemplate; //copy same itemtemplate as original / main list

                if (IsNewCheck == false) // move menu items only when not adding from this page
                {
                    MoveItemsInChecks(lvMenuItems, lstMenuItems); //move menu items from main check to appropriate check
                }

                Grid.SetRow(lstMenuItems, 2);
                GridSplitCheck.Children.Add(lstMenuItems);

                #endregion

                #region create footer row

                /*create footer row*/
                Grid GridSplitCheckFooter = new Grid();
                GridSplitCheckFooter.Background = new SolidColorBrush(Colors.LightGray);
                gridCol1 = new ColumnDefinition();
                gridCol2 = new ColumnDefinition();

                GridSplitCheckFooter.ColumnDefinitions.Add(gridCol1);
                GridSplitCheckFooter.ColumnDefinitions.Add(gridCol2);

                lblHeader1 = new TextBlock();
                lblHeader1.Text = "Subtotal";
                lblHeader1.FontSize = 20;
                lblHeader1.Margin = new Thickness(5, 4, 0, 0);
                Grid.SetColumn(lblHeader1, 0);

                TextBlock lblOrderTotal = new TextBlock();
                decCurrentTotal = 0; 
                decimal iTotal = 0; 
                decimal iDetailDiscountTotal = 0; // Discount  Total if discount is item wise 

                foreach (OrderData od in lstMenuItems.Items)
                {
                    decCurrentTotal += od.Price;
                    iDetailDiscountTotal += (od.Price - await CommonUtility.CalculateDiscount(od.Price, od.DiscountID));  // Calculate detail discount 
                }

                iTotal = decCurrentTotal - iDetailDiscountTotal;
                decCurrentTotal = (iTotal - await CommonUtility.CalculateDiscount(iTotal, iOrderDiscount, iSplitCount));  // Calculate discount 
                iTotal = iTotal - (decCurrentTotal);


                lblOrderTotal.Text = iTotal.ToString("N");
                lblOrderTotal.FontSize = 28;
                lblOrderTotal.HorizontalAlignment = HorizontalAlignment.Left;
                lblOrderTotal.Margin = new Thickness(0, 4, 0, 0);
                lblOrderTotal.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                Grid.SetColumn(lblOrderTotal, 1);

                TextBlock lblDiscountTotal = new TextBlock();
                lblDiscountTotal.Text = iTotal.ToString("N");
                lblDiscountTotal.Inlines.Add(new Run() { Text = (IsDiscount == false ? "" : "(" + (iDetailDiscountTotal + decCurrentTotal).ToString("N") + ")"), Foreground = new SolidColorBrush(Colors.Red) });
                lblDiscountTotal.FontSize = 20;
                lblDiscountTotal.HorizontalAlignment = HorizontalAlignment.Right;
                lblDiscountTotal.Width = 140;
                lblDiscountTotal.TextAlignment = TextAlignment.Right;
                lblDiscountTotal.Margin = new Thickness(0, 4, 5, 0);
                Grid.SetColumn(lblDiscountTotal, 1);


                GridSplitCheckFooter.Children.Add(lblHeader1);
                GridSplitCheckFooter.Children.Add(lblOrderTotal);
                GridSplitCheckFooter.Children.Add(lblDiscountTotal);

                Grid.SetRow(GridSplitCheckFooter, 3);
                GridSplitCheck.Children.Add(GridSplitCheckFooter);

                #endregion

                #region create header strip row for Payment method


                /*create header strip row for Payment method*/
                Grid GridCloseCheckTypeStrip = new Grid();
                GridCloseCheckTypeStrip.Height = 260;
                GridCloseCheckTypeStrip.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                GridCloseCheckTypeStrip.Background = new SolidColorBrush(Colors.White);
                ColumnDefinition GridCloseCheckTypeStripColstrip1 = new ColumnDefinition();
                GridCloseCheckTypeStrip.ColumnDefinitions.Add(GridCloseCheckTypeStripColstrip1);

                ColumnDefinition GridCloseCheckTypeStripColstrip2 = new ColumnDefinition();
                GridCloseCheckTypeStripColstrip2.Width = new GridLength(180);
                GridCloseCheckTypeStrip.ColumnDefinitions.Add(GridCloseCheckTypeStripColstrip2);

                RowDefinition GridCloseCheckTypeStrip1 = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridCloseCheckTypeStrip1);

                RowDefinition GridRowForPaymentMode = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForPaymentMode);

                RowDefinition GridRowForTip = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForTip);
                RowDefinition GridRowFortax = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowFortax);
                RowDefinition GridRowForTotal = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForTotal);
                RowDefinition GridRowForpayment = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForpayment);
                RowDefinition GridRowForChange = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForChange);
                RowDefinition GridRowForAuthCode = new RowDefinition();
                GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForAuthCode);

               


                #region Payment method

                TextBlock lblHeaderGridCloseCheckType = new TextBlock();
                lblHeaderGridCloseCheckType.Text = "Payment method";
                lblHeaderGridCloseCheckType.FontSize = 20;
                lblHeaderGridCloseCheckType.Margin = new Thickness(5, 4, 0, 0);
                Grid.SetRow(lblHeaderGridCloseCheckType, 0);
                Grid.SetColumnSpan(lblHeaderGridCloseCheckType, 2);
                GridCloseCheckTypeStrip.Children.Add(lblHeaderGridCloseCheckType);

                RadioButton rdbHeaderGridCloseCheckType1 = new RadioButton();
                rdbHeaderGridCloseCheckType1.CommandParameter = "Cash";
                rdbHeaderGridCloseCheckType1.Name = "Cash" + CheckCount;
                rdbHeaderGridCloseCheckType1.IsChecked = Globals.OrderCheckRecords[CheckCount].col_PaymentType == 0 ? true : false;
                rdbHeaderGridCloseCheckType1.GroupName = CheckCount.ToString();
                rdbHeaderGridCloseCheckType1.Content = "Cash";
                rdbHeaderGridCloseCheckType1.FontSize = 20;
                rdbHeaderGridCloseCheckType1.Margin = new Thickness(0);
                rdbHeaderGridCloseCheckType1.Padding = new Thickness(3, -2, 0, 0);
                rdbHeaderGridCloseCheckType1.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                rdbHeaderGridCloseCheckType1.Checked += rdbHeaderGridCloseCheckType1_Checked;

                Grid.SetRow(rdbHeaderGridCloseCheckType1, 1);
                Grid.SetColumn(rdbHeaderGridCloseCheckType1, 0);
                GridCloseCheckTypeStrip.Children.Add(rdbHeaderGridCloseCheckType1);

                RadioButton rdbHeaderGridCloseCheckType2 = new RadioButton();
                rdbHeaderGridCloseCheckType2.CommandParameter = "CreditDebit";
                rdbHeaderGridCloseCheckType2.IsChecked = Globals.OrderCheckRecords[CheckCount].col_PaymentType == 1 ? true : false;
                rdbHeaderGridCloseCheckType2.Content = "Credit/Debit";
                rdbHeaderGridCloseCheckType2.Name = "CreditDebit" + CheckCount;
                rdbHeaderGridCloseCheckType2.GroupName = CheckCount.ToString();
                rdbHeaderGridCloseCheckType2.FontSize = 20;
                rdbHeaderGridCloseCheckType2.Margin = new Thickness(0);
                rdbHeaderGridCloseCheckType2.Padding = new Thickness(3, -2, 0, 0);
                rdbHeaderGridCloseCheckType2.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                rdbHeaderGridCloseCheckType2.Checked += rdbHeaderGridCloseCheckType1_Checked;

                Grid.SetRow(rdbHeaderGridCloseCheckType2, 1);
                Grid.SetColumn(rdbHeaderGridCloseCheckType2, 1);
                GridCloseCheckTypeStrip.Children.Add(rdbHeaderGridCloseCheckType2);

                #endregion

                #region Tip

                TextBlock lbltip = new TextBlock();
                lbltip.Text = "Tip";
                lbltip.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lbltip.FontSize = 20;
                lbltip.Margin = new Thickness(5, 4, 4, 0);
                Grid.SetRow(lbltip, 2);
                Grid.SetColumn(lbltip, 0);
                GridCloseCheckTypeStrip.Children.Add(lbltip);

                TextBox txtTip = new TextBox();
                txtTip.Name = "txtTip" + CheckCount;
                txtTip.TextChanged += txtTip_TextChanged;
                txtTip.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtTip.Width = 150;
                txtTip.Text = Globals.OrderCheckRecords[CheckCount].col_Gratuity.ToString("N");
                txtTip.FontSize = 20;
                txtTip.Margin = new Thickness(5, -3, 0, 0);
                txtTip.MaxLength = 9;
                Grid.SetRow(txtTip, 2);
                Grid.SetColumn(txtTip, 1);
                GridCloseCheckTypeStrip.Children.Add(txtTip);

                #endregion

                #region Tax

                TextBlock lblTax = new TextBlock();
                lblTax.Text = "Tax";
                lblTax.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lblTax.FontSize = 20;
                lblTax.Margin = new Thickness(5, 4, 4, 0);
                Grid.SetRow(lblTax, 3);
                Grid.SetColumn(lblTax, 0);
                GridCloseCheckTypeStrip.Children.Add(lblTax);

                TextBlock txtTax = new TextBlock();
                txtTax.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtTax.Width = 150;
                txtTax.Text = Globals.OrderCheckRecords[CheckCount].col_Tax.ToString("N");
                txtTax.FontSize = 20;
                txtTax.Margin = new Thickness(16, 4, 0, 0);
                Grid.SetRow(txtTax, 3);
                Grid.SetColumn(txtTax, 1);
                GridCloseCheckTypeStrip.Children.Add(txtTax);

                #endregion

                #region Total

                TextBlock lblTotal = new TextBlock();
                lblTotal.Text = "Total";
                lblTotal.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lblTotal.FontSize = 20;
                lblTotal.Margin = new Thickness(5, 4, 4, 0);
                Grid.SetRow(lblTotal, 4);
                Grid.SetColumn(lblTotal, 0);
                GridCloseCheckTypeStrip.Children.Add(lblTotal);

                TextBlock txtTotal = new TextBlock();
                txtTotal.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtTotal.Width = 150;

                decimal dTip, dTotal;
                // Get the gratuity...
                try
                {
                    dTip = Convert.ToDecimal(txtTip.Text);
                }
                catch (FormatException)
                {
                    dTip = 0;
                }

                // Determine the total, based on subtotal, tax, and tip
                dTotal = iTotal + Convert.ToDecimal(txtTax.Text) + dTip;
                txtTotal.Text = Convert.ToDecimal(dTotal).ToString("N");

                txtTotal.FontSize = 20;
                txtTotal.Margin = new Thickness(16, 4, 0, 0);
                Grid.SetRow(txtTotal, 4);
                Grid.SetColumn(txtTotal, 1);
                GridCloseCheckTypeStrip.Children.Add(txtTotal);

                #endregion

                #region Payment


                TextBlock lblPayment = new TextBlock();
               
                lblPayment.Text = "Payment ";
                lblPayment.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lblPayment.FontSize = 20;
                lblPayment.Margin = new Thickness(5, 4, 5, 0);
                Grid.SetRow(lblPayment, 5);
                Grid.SetColumn(lblPayment, 0);
                GridCloseCheckTypeStrip.Children.Add(lblPayment);

                TextBox txtPayment = new TextBox();
                txtPayment.Name = "txtPayment" + CheckCount;
                txtPayment.TextChanged += txtTip_TextChanged;
                txtPayment.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtPayment.Width = 150;
                txtPayment.Text = Globals.OrderCheckRecords[CheckCount].col_AmountTendered.ToString("N");
                txtPayment.FontSize = 20;
                txtPayment.Margin = new Thickness(5, -3, 0, 0);
                txtPayment.MaxLength = 10;
                Grid.SetRow(txtPayment, 5);
                Grid.SetColumn(txtPayment, 1);
                GridCloseCheckTypeStrip.Children.Add(txtPayment);

                #endregion

                #region Change

                TextBlock lblChange = new TextBlock();
                lblChange.Text = "Change ";
                lblChange.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lblChange.FontSize = 20;
                lblChange.Margin = new Thickness(5, 4, 5, 0);
                Grid.SetRow(lblChange, 6);
                Grid.SetColumn(lblChange, 0);
                GridCloseCheckTypeStrip.Children.Add(lblChange);

                TextBox txtChange = new TextBox();
                txtChange.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtChange.Width = 150;
                decimal change = (Convert.ToDecimal(Globals.OrderCheckRecords[CheckCount].col_AmountTendered) - dTotal);
                change = (change < 0 ? 0 : change);
                txtChange.Text = change.ToString("N");
                txtChange.FontSize = 20;
                txtChange.Margin = new Thickness(5, -3, 0, 0);
                txtChange.IsEnabled = false;
                Grid.SetRow(txtChange, 6);
                Grid.SetColumn(txtChange, 1);
                GridCloseCheckTypeStrip.Children.Add(txtChange);

                #endregion

                #region Auth code

                TextBlock lblAuthCode = new TextBlock();
                lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblAuthCode.Text = "Auth Code ";
                lblAuthCode.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                lblAuthCode.FontSize = 20;
                lblAuthCode.Margin = new Thickness(5, 4, 5, 0);
                Grid.SetRow(lblAuthCode, 7);
                Grid.SetColumn(lblAuthCode, 0);
                GridCloseCheckTypeStrip.Children.Add(lblAuthCode);

                TextBox txtAuthCode = new TextBox();
                txtAuthCode.Name = "txtAuthCode" + CheckCount;
                txtAuthCode.TextChanged += txtAuthCode_TextChanged;
                txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                txtAuthCode.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                txtAuthCode.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                txtAuthCode.Width = 150;
                txtAuthCode.Height = 35;
                txtAuthCode.Text = Globals.OrderCheckRecords[CheckCount].col_AuthCode == null ? "" : Globals.OrderCheckRecords[CheckCount].col_AuthCode;
                txtAuthCode.FontSize = 20;
                txtAuthCode.Margin = new Thickness(5, -3, 0, 0);
                txtAuthCode.MaxLength = 50;
                Grid.SetRow(txtAuthCode, 7);
                Grid.SetColumn(txtAuthCode, 1);
                GridCloseCheckTypeStrip.Children.Add(txtAuthCode);

                #endregion


                Grid.SetRow(GridCloseCheckTypeStrip, 4);
                GridSplitCheck.Children.Add(GridCloseCheckTypeStrip);

                #endregion


                #region create footer for button

                /*create footer for button*/
                Grid GridSplitCheckFooterForbutton = new Grid();
                GridSplitCheckFooterForbutton.Background = new SolidColorBrush(Colors.White);
                gridCol1 = new ColumnDefinition();
                gridCol2 = new ColumnDefinition();

                GridSplitCheckFooterForbutton.ColumnDefinitions.Add(gridCol1);
                GridSplitCheckFooterForbutton.ColumnDefinitions.Add(gridCol2);

                // Set remove button 
                Button btnCloseCheck = new Button() { Content = "Close", CommandParameter = CheckCount, FontSize = 20 };
                btnCloseCheck.Tapped += btnCloseCheck_Tapped;
               
                ToolTip toolTip = new ToolTip();
                toolTip.Content = "Close check";
                ToolTipService.SetToolTip(btnCloseCheck, toolTip);
                btnCloseCheck.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                btnCloseCheck.Width = 120;
                btnCloseCheck.Height = 80;
                btnCloseCheck.Margin = new Thickness(5, 4, 0, 0);
                Grid.SetColumn(btnCloseCheck, 0);
                GridSplitCheckFooterForbutton.Children.Add(btnCloseCheck);


                // Set remove button 
                Button btnPrintCheck = new Button() { Content = "Print", CommandParameter = CheckCount, FontSize = 20 };
                btnPrintCheck.Tapped += btnPrintCheck_Tapped;
                
                toolTip = new ToolTip();
                toolTip.Content = "Print check";
                ToolTipService.SetToolTip(btnPrintCheck, toolTip);
                btnPrintCheck.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                btnPrintCheck.Width = 120;
                btnPrintCheck.Height = 80;
                btnPrintCheck.HorizontalAlignment = HorizontalAlignment.Right;
                btnPrintCheck.Margin = new Thickness(0, 4, 5, 0);
                Grid.SetColumn(btnPrintCheck, 1);
                GridSplitCheckFooterForbutton.Children.Add(btnPrintCheck);

                Grid.SetRow(GridSplitCheckFooterForbutton, 5);
                GridSplitCheck.Children.Add(GridSplitCheckFooterForbutton);

                #endregion

                

                tmpBorder.Child = GridSplitCheck;
                tmpCanvas.Children.Add(tmpBorder);
                
                if (CheckCount > 2) SplitChecksContainer.Width = SplitChecksContainer.Width + 300;

                Thumb thumb = new Thumb();

                tmpCanvas.Children.Add(thumb);

                SplitChecksContainer.Children.Add(tmpCanvas);
                // set payment mode radio button click based on saved option
                rdbHeaderGridCloseCheckType1_Checked(rdbHeaderGridCloseCheckType1.IsChecked == true ? rdbHeaderGridCloseCheckType1 : rdbHeaderGridCloseCheckType2, null);
                if (Globals.OrderCheckRecords[CheckCount].col_Paid) EnableDisable_SplitCheckControls(CheckCount);
                else
                {
                    btnCloseCheck.IsEnabled = change > 0;
                    btnPrintCheck.IsEnabled = change > 0;
                }
                SplitChecksContainer.UpdateLayout();
            }
            catch (Exception ex)
            {
                iSplitCount = SplitChecksContainer.Children.Count;
            }
        }

       async void txtAuthCode_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender == null) return;

            string name = ((Windows.UI.Xaml.FrameworkElement)(sender)).Name;
            if (string.IsNullOrWhiteSpace(name)) return;

            string checkNo = name.Remove(0, 11) ; // check this is from tip or payment textbox 

            if (string.IsNullOrWhiteSpace(checkNo)) return;

            Grid childGrid = GetPaymentGridFromCheckNo(checkNo);
            await calculatePayment(childGrid, -1, true);


        }

        void btnCloseCheck_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button btnCross = sender as Button;
            if (btnCross != null) CloseCheck(btnCross.CommandParameter);
        }        

        void btnPrintCheck_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button btnCross = sender as Button;
            if (btnCross != null) PrintCheck(btnCross.CommandParameter);
        }

        private async void CloseCheck(object checkNo)
        {

            // Display the wait page...
            WaitPage waitPage = new WaitPage();
            waitPage.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            waitPage.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Popup dialogPopup = new Popup();
            dialogPopup.Child = waitPage;
            

            if (checkNo == null)
                return;
            
            try {

                dialogPopup.IsOpen = true;
                string checkNumber = Convert.ToString(checkNo);

                Grid childGrid = GetPaymentGridFromCheckNo(checkNumber);
                if (childGrid == null) return  ;

                await calculatePayment(childGrid, Convert.ToInt32(checkNumber));

                //Disable  buttons 
                FooterButtonsEnableDisable(Convert.ToInt32(checkNumber), false);

                bool bAllPaid = true;
                foreach (ServiceReferenceOpenRPOS.OrderCheck oc in Globals.OrderCheckRecords)
                {
                    if (oc.col_Paid) EnableDisable_SplitCheckControls(oc.col_SeatNumber);
                    bAllPaid &= oc.col_Paid;
                }

                // Close the entire order if all checks have been paid...
                // Send close request    
                if (this.CloseRequested != null && bAllPaid)
                {
                    this.CloseRequested(this, EventArgs.Empty);
                }
            }
            catch(Exception ex)
            {
                dialogPopup.IsOpen = false;
            }

            finally
            {
                dialogPopup.IsOpen = false;
            }            
        }

        void FooterButtonsEnableDisable(int checkNo, bool isEnable)
        {
            Grid childGrid = GetPaymentGridFromCheckNo(checkNo.ToString());
            if (childGrid == null) return;

            Grid childFooterButtonGrid = ((Grid)(((Panel)(childGrid)).Children[5]));
            if (childFooterButtonGrid != null)
            {
                Button btnClose = ((Button)childFooterButtonGrid.Children[0]) as Button;
                Button btnPrint = ((Button)childFooterButtonGrid.Children[1]) as Button;

                if (btnClose != null) btnClose.IsEnabled = isEnable;
                if (btnPrint != null) btnPrint.IsEnabled = isEnable;
            }

            EnabledisablePaidImage(isEnable, checkNo);
        }

        private async void PrintCheck(object checkNo)
        {

            // Display the wait page...
            WaitPage waitPage = new WaitPage();
            waitPage.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            waitPage.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Popup dialogPopup = new Popup();
            dialogPopup.Child = waitPage;

            try
            {
                if (checkNo == null)
                    return;
                
                dialogPopup.IsOpen = true;

                int checkNumber = Convert.ToInt32(checkNo);
                int tmpCount = 0;
                while (tmpCount < iSplitCount)
                {

                    Grid childGrid = GetPaymentGridFromCheckNo(tmpCount.ToString());
                    if (childGrid == null) continue;

                    await calculatePayment(childGrid, tmpCount, true);
                    tmpCount++;
                }

                //Disable  buttons 
                FooterButtonsEnableDisable(checkNumber, true);



                Globals.OrderCheckRecords = await Globals.client.GetOrderCheckObjectsAsync(Globals.token, "OrderSummaryID=" + iOrderNO + " ORDER BY SeatNumber");
                // Remove any excess records, if they exist
                if (Globals.OrderCheckRecords.Count() > iSplitCount)
                {
                    int cnt = Globals.OrderCheckRecords.Count();
                    for (int i = cnt; cnt > iSplitCount; cnt--)
                    {
                        await Globals.client.DeleteOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[cnt - 1]);
                        Globals.OrderCheckRecords.RemoveAt(cnt - 1);
                    }
                }

                // Update the print queue to print the order reciepts
                ServiceReferenceOpenRPOS.PrintQueue pq = new ServiceReferenceOpenRPOS.PrintQueue();
                pq.bFilterPrintOrder = true;
                pq.col_PrintOrder = false;
                pq.bFilterPrintReceipt = true;
                pq.col_PrintReceipt = true;
                pq.bFilterOrderCheckID = true;
                pq.col_OrderCheckID = Globals.OrderCheckRecords[checkNumber].col_ID;
                pq.bFilterOrderSummaryID = true;
                pq.col_OrderSummaryID = iOrderNO;
                pq.bFilterPrinted = true;
                pq.col_Printed = false;
                await Globals.client.AddPrintQueueObjectAsync(Globals.token, pq);
            }
            catch(Exception ex)
            {
                 dialogPopup.IsOpen = false;
            }
            finally{
             dialogPopup.IsOpen = false;
            }
        }

        async void txtTip_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender == null) return;

            string name = ((Windows.UI.Xaml.FrameworkElement)(sender)).Name;
            if (string.IsNullOrWhiteSpace(name)) return;

            string checkNo = (name.Contains("txtTip") ? name.Remove(0, 6) : name.Remove(0, 10)); // check this is from tip or payment textbox 
            
            if (string.IsNullOrWhiteSpace(checkNo)) return;

            Grid childGrid = GetPaymentGridFromCheckNo(checkNo);
            await calculatePayment(childGrid,-1,true);
            
            // Check value is Numeric or not  if it is non numeric , set to 0 
            try{
                 decimal d = Convert.ToDecimal(((TextBox)sender).Text);
            }
            catch{
                ((TextBox)sender).Text = "0.00";
            }
        }

        private async Task<bool> calculatePayment(Grid childGrid,  int checkNo =-1, bool fromPaymentChange=false)
        {
            if (childGrid == null) return false;

            decimal dTip=0, dTotal=0, tax=0, payment=0;


            Grid childFooterGrid = ((Grid)(((Panel)(childGrid)).Children[3]));
            if (childFooterGrid != null)
            {
                // Get Sub Total 
                TextBlock lblTotal = ((TextBlock)childFooterGrid.Children[1]) as TextBlock;
                if (lblTotal != null) dTotal = Convert.ToDecimal(lblTotal.Text);
            }

            Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
            if (childPaymentGrid != null)
            {

                RadioButton rdCash = ((RadioButton)childPaymentGrid.Children[1]) as RadioButton;
                RadioButton rdCreditDebit = ((RadioButton)childPaymentGrid.Children[2]) as RadioButton;

                TextBox txtTip = ((TextBox)childPaymentGrid.Children[4]) as TextBox;

                TextBlock txtTax = ((TextBlock)childPaymentGrid.Children[6]) as TextBlock;
                TextBlock txtTotal = ((TextBlock)childPaymentGrid.Children[8]) as TextBlock;
                TextBox txtPayment = ((TextBox)childPaymentGrid.Children[10]) as TextBox;
                TextBox txtChange = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[14]) as TextBox;

                
                if (txtTip != null)
                {
                    // Get the gratuity...
                    try
                    {
                        dTip = Convert.ToDecimal(txtTip.Text);
                    }
                    catch (FormatException)
                    {
                        dTip = 0;
                    }
                }

                if (txtTax != null)
                {
                    // Get the Tax...
                    try
                    {
                        tax = Convert.ToDecimal(txtTax.Text);
                    }
                    catch (FormatException)
                    {
                        tax = 0;
                    }
                }

                if (txtTotal != null) txtTotal.Text = (dTotal + tax + dTip).ToString("N");

                if (txtPayment != null)
                {
                    // Get the Payment...
                    try
                    {
                        payment = Convert.ToDecimal(txtPayment.Text);
                    }
                    catch (FormatException)
                    {
                        payment = 0;
                    }
                }


                // get Change 
                decimal dChange = payment - (dTotal + tax + dTip) ;
                dChange = (dChange < 0) ? 0 : dChange;

                

                if (txtChange != null) txtChange.Text = (dChange).ToString("N");
                string Authcode = string.Empty;
                if (txtAuthCode != null) Authcode = txtAuthCode.Text; // Add Auth code 
                bool ispaid = false;

                if (rdCreditDebit != null && rdCreditDebit.IsChecked == true)
                    ispaid = (string.IsNullOrWhiteSpace(Authcode)== false);
                else if (rdCash != null && rdCash.IsChecked == true)
                    ispaid = (payment - (dTotal + tax + dTip) >= 0);
             
                // Save order details  if it is from ok button 
                if (checkNo > -1)
                {
                    Globals.OrderCheckRecords[checkNo].col_Gratuity = dTip; // Set Gratuity 
                    Globals.OrderCheckRecords[checkNo].bFilterGratuity = true;
                   
                    Globals.OrderCheckRecords[checkNo].col_Tax = tax;  // Set tax
                    Globals.OrderCheckRecords[checkNo].bFilterTax = true;
                    Globals.OrderCheckRecords[checkNo].col_Subtotal = dTotal;  // Set  Sub total 
                    Globals.OrderCheckRecords[checkNo].bFilterSubtotal = true;
                    Globals.OrderCheckRecords[checkNo].col_SeatNumber = Convert.ToByte(checkNo);
                    Globals.OrderCheckRecords[checkNo].bFilterSeatNumber = true;
                    Globals.OrderCheckRecords[checkNo].bFilterPaymentType = true;

                   
                    if (rdCreditDebit != null &&  rdCreditDebit.IsChecked == true )
                    {
                        Globals.OrderCheckRecords[checkNo].bFilterPaid = ispaid;
                        if (txtAuthCode != null) Globals.OrderCheckRecords[checkNo].col_AuthCode = txtAuthCode.Text; // Add Auth code 
                        Globals.OrderCheckRecords[checkNo].bFilterAuthCode = true;
                        Globals.OrderCheckRecords[checkNo].col_PaymentType = 1;  // Set payment type 1 for Creditdebit
                    }
                    else if (rdCash != null && rdCash.IsChecked == true)
                    {
                        Globals.OrderCheckRecords[checkNo].col_PaymentType = 0;  // Set payment type 0 for Cash 
                        Globals.OrderCheckRecords[checkNo].bFilterPaid = ispaid;
                        Globals.OrderCheckRecords[checkNo].col_AmountTendered = payment; // Set AmountTendered
                        Globals.OrderCheckRecords[checkNo].bFilterAmountTendered = true;
                    }
                }

                if (fromPaymentChange && checkNo <0)
                {
                    Grid childFooterButtonGrid = ((Grid)(((Panel)(childGrid)).Children[5]));
                    if (childFooterButtonGrid != null)
                    {
                        Button btnClose = ((Button)childFooterButtonGrid.Children[0]) as Button;
                        Button btnPrint = ((Button)childFooterButtonGrid.Children[1]) as Button;

                        if (btnClose != null) btnClose.IsEnabled = ispaid;
                        if (btnPrint != null) btnPrint.IsEnabled = ispaid;
                    }
                }


                // Save order details  if it is from ok button 
                if (checkNo > -1)
                {
                    if (!fromPaymentChange)                    
                    {
                        Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        if (Globals.OrderCheckRecords[checkNo].col_Paid) EnableDisable_SplitCheckControls(checkNo);
                    }
                    else if (txtPayment != null && txtAuthCode != null)
                    {
                        if ((txtPayment.IsEnabled == false || txtAuthCode.IsEnabled == false) && ispaid)
                        {
                            Globals.OrderCheckRecords[checkNo].bFilterPaid = ispaid;
                            Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        }
                    }

                    // Send the updated record...
                    if (checkNo == Globals.OrderCheckRecords[checkNo].col_SeatNumber)
                    {
                        if (Globals.OrderCheckRecords[checkNo].col_ID == 0)
                            // Need to add a new record
                            await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[checkNo]);
                        else
                            // Update this record
                            await Globals.client.UpdateOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[checkNo]);
                    }
                }

               
            }

            return true;
        }

        private Grid GetPaymentGridFromCheckNo(string checkNo)
        {
            Canvas selectedControl = SplitChecksContainer.Children[Convert.ToInt32(checkNo)] as Canvas;

            if (selectedControl != null)
            {
                Border childBorder = ((Border)(((Panel)(selectedControl)).Children[0]));
                if (childBorder == null) return null;

                if (childBorder.Child != null)
                {
                    return childBorder.Child as Grid;
                }
            }

            return null;
        }

        void rdbHeaderGridCloseCheckType1_Checked(object sender, RoutedEventArgs e)
        {
            string parameter = Convert.ToString(((Windows.UI.Xaml.Controls.Primitives.ButtonBase)(sender)).CommandParameter);
            string Checkno = Convert.ToString(((RadioButton)(sender)).GroupName);

            // check if check number and radio button  are  valid
            if (string.IsNullOrWhiteSpace(Checkno) || string.IsNullOrWhiteSpace(parameter))
            {
                return;
            }


            Grid childGrid = GetPaymentGridFromCheckNo(Checkno);
            if (childGrid != null)
            {
                Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
                if (childPaymentGrid != null)
                {
                    TextBlock lblPayment = ((TextBlock)childPaymentGrid.Children[9]) as TextBlock;
                    TextBox txtPayment = ((TextBox)childPaymentGrid.Children[10]) as TextBox;
                    TextBlock lblChange = ((TextBlock)childPaymentGrid.Children[11]) as TextBlock;
                    TextBox txtChange = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                    TextBlock lblAuthCode = ((TextBlock)childPaymentGrid.Children[13]) as TextBlock;
                    TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[14]) as TextBox;

                    childPaymentGrid.RowDefinitions[7].Height = new GridLength(0);
                    childPaymentGrid.RowDefinitions[6].Height = new GridLength(0);
                    childPaymentGrid.RowDefinitions[5].Height = new GridLength(0);


                    if (lblPayment != null) lblPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtPayment != null) txtPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (lblChange != null) lblChange.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtChange != null) txtChange.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (lblAuthCode != null) lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtAuthCode != null) txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;


                    switch (parameter)
                    {
                        case "Cash":
                            if (lblPayment != null) lblPayment.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (txtPayment != null) txtPayment.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (lblChange != null) lblChange.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (txtChange != null) txtChange.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            childPaymentGrid.RowDefinitions[6].Height = new GridLength(35);
                            childPaymentGrid.RowDefinitions[5].Height = new GridLength(35);
                            childPaymentGrid.Height = 230;
                            break;
                        case "CreditDebit":
                            if (lblAuthCode != null) lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (txtAuthCode != null) txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            childPaymentGrid.RowDefinitions[7].Height = new GridLength(70);
                            childPaymentGrid.Height = 230;
                            break;
                    }
                }
            }
        }
        
        private void MoveItemsInChecks(ListView SenderListview, ListView ReceiverListview)
        {
            if (ReceiverListview == null || SenderListview == null) return; //return and do nothing, if source or destination list object is null or not create 
            int checkNo = Convert.ToInt32(ReceiverListview.Tag);
            List<object> selectedItems = new List<object>();
            foreach (OrderData od in SenderListview.Items)
            {
                if (od.Parent != null) continue;

                if (od.SeatNumber == checkNo)
                {
                    od.SeatNumber = checkNo;
                    ReceiverListview.Items.Add(od);
                    selectedItems.Add(od);
                    if (od.Options != null)
                    {
                        foreach (OrderData odt in od.Options)
                        {
                            ReceiverListview.Items.Add(odt);
                            od.SeatNumber = checkNo;
                            selectedItems.Add(od);
                        }
                    }
                }
            }

            foreach (OrderData od in selectedItems)
            {
                if (od.Options != null)
                {
                    foreach (OrderData odt in od.Options)
                    {
                        SenderListview.Items.Remove(odt);
                    }
                }

                SenderListview.Items.Remove(od);
            }
        }
        

        public void setHeaderText(string strHeaderText)
        {
            lblOrderNo.Text = Convert.ToString(iOrderNO);
            lblTableNo.Text = Convert.ToString(iTableNO);
        }
        
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.CloseRequested(this, null);
        }

        void EnabledisablePaidImage(bool isEnable, int checkNo)
        {
            Canvas selectedControl = SplitChecksContainer.Children[Convert.ToInt32(checkNo)] as Canvas;
            if (selectedControl != null)
            {

                Thumb cThumb = selectedControl.Children[1] as Thumb;
                if (cThumb != null)
                {
                    if (isEnable == false)
                    {
                        cThumb.Style = this.Resources["MyThumbStyle"] as Style;
                        cThumb.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.Height = 800;
                        cThumb.Width = 300;
                    }
                    else
                    {
                        cThumb.Style = null;
                        cThumb.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.Height = 0;
                        cThumb.Width = 0;
                    }
                }
            }
            

        }

        private void EnableDisable_SplitCheckControls(int checkNo)
        {

            bool isEnable = !Globals.OrderCheckRecords[checkNo].col_Paid;

            EnabledisablePaidImage(isEnable, checkNo);  // Set paid image 
            
            Grid childGrid = GetPaymentGridFromCheckNo(Convert.ToString(checkNo));
            if (childGrid == null) return;
           

            Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
            if (childPaymentGrid != null)
            {

                RadioButton rdCash = ((RadioButton)childPaymentGrid.Children[1]) as RadioButton;
                RadioButton rdCreditDebit = ((RadioButton)childPaymentGrid.Children[2]) as RadioButton;

                TextBox txtTip = ((TextBox)childPaymentGrid.Children[4]) as TextBox;
                TextBox txtPayment = ((TextBox)childPaymentGrid.Children[10]) as TextBox;
                TextBox txtChange = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[14]) as TextBox;

                if (rdCash != null) rdCash.IsEnabled = isEnable;
                if (rdCreditDebit != null) rdCreditDebit.IsEnabled = isEnable;
                if (txtTip != null) txtTip.IsEnabled = isEnable;
                if (txtPayment != null) txtPayment.IsEnabled = isEnable;
                if (txtAuthCode != null) txtAuthCode.IsEnabled = isEnable;


            }

            Grid childFooterButtonGrid = ((Grid)(((Panel)(childGrid)).Children[5]));
            if (childFooterButtonGrid != null)
            {
                Button btnClose = ((Button)childFooterButtonGrid.Children[0]) as Button;
                Button btnPrint = ((Button)childFooterButtonGrid.Children[1]) as Button;

                if (btnClose != null) btnClose.IsEnabled = isEnable;
                if (btnPrint != null) btnPrint.IsEnabled = isEnable;
            }
        }
    }
}
